package nia.chapter13.broadcat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import nia.chapter13.entity.LogEvent;

import java.io.File;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;

/**
 * 广播者
 * 代码清单 13-3 LogEventBroadcaster
 *
 * @author <a href="mailto:norman.maurer@gmail.com">Norman Maurer</a>
 */
public class LogEventBroadcaster {
    private final EventLoopGroup group;
    private final Bootstrap bootstrap;

    public LogEventBroadcaster(InetSocketAddress address) {
        group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        //引导该 NioDatagramChannel（无连接的）
        bootstrap.group(group).channel(NioDatagramChannel.class)
                //设置 SO_BROADCAST 套接字选项
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new LogEventEncoder(address));
    }

    public void run(int bindPort) throws Exception {
        //绑定 Channel
        //监听器端口号和广播者绑定的端口号不能一致
        Channel ch = bootstrap.bind(bindPort).sync().channel();
        long pointer = 0;
        //启动主处理循环
        for (int i = 0; i < 10; i++) {
            //对于每个日志条目，写入一个 LogEvent 到 Channel 中
            LogEvent logEvent = new LogEvent(null, -1, "c:/file/file1", "你好");
            ch.writeAndFlush(logEvent);
            try {
                //休眠 1 秒，如果被中断，则退出循环；否则重新处理它
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.interrupted();
                break;
            }
        }
    }

    public void stop() {
        group.shutdownGracefully();
    }

    public static void main(String[] args) throws Exception {
        //广播到特定的端口号
        InetSocketAddress address = new InetSocketAddress("255.255.255.255", 9999);
        //创建并启动一个新的 LogEventBroadcaster 的实例
        LogEventBroadcaster broadcaster = new LogEventBroadcaster(address);
        try {
            for (int i = 0; i < 10; i++) {
                broadcaster.run(i);
            }
        } finally {
            broadcaster.stop();
        }
    }
}
